﻿using System;
using TMPro;
using UnityEngine;

public abstract class CardViewBase : MonoBehaviour
{
    public Card card;

    [SerializeField] private Animator animator;
    [SerializeField] private TMP_Text title;
    [SerializeField] private TMP_Text description;
    [SerializeField] private TMP_Text mana;
    public int ManaNumber;

    public EffectSystem effectSystem;

    private const string effectNamespace = "";

    /// <summary>
    /// 初始化 Card
    /// </summary>
    protected void SetupInternal(Card newCard)
    {
        card = newCard;
        CreateEffectSystem();
        effectSystem?.Setup(card.ProNumber);
        InitializeAnimatorController();
        Refresh();
    }

    /// <summary>
    /// 创建效果系统
    /// </summary>
    private void CreateEffectSystem()
    {
        if (card == null) return;

        string className = effectNamespace + card.Title + "EffectSystem";
        Type type = Type.GetType(className);
        if (type != null)
            effectSystem = Activator.CreateInstance(type) as EffectSystem;
        else
            Debug.LogWarning($"EffectSystem 类型 {className} 未找到");
    }

    /// <summary>
    /// 刷新 UI
    /// </summary>
    public virtual void Refresh()
    {
        effectSystem?.Setup(card.ProNumber);
        title.text = card.Title;
        description.text = effectSystem.Description;
        mana.text = effectSystem.Mana.ToString();
        ManaNumber = effectSystem.Mana;
        // Debug.Log($"[Refresh]card.ProNumber={card.ProNumber} card.Title={card.Title}, titleComponent={(title == null ? "NULL" : title.text)} {ManaNumber}");
    }

    /// <summary>
    /// 初始化 Animator
    /// </summary>
    private void InitializeAnimatorController()
    {
        if (card == null || animator == null) return;

        string path = $"Card/{card.Title}/{card.Title}_AC";
        RuntimeAnimatorController controller = Resources.Load<RuntimeAnimatorController>(path);
        if (controller != null)
            animator.runtimeAnimatorController = controller;
        else
            Debug.LogWarning($"Animator Controller 未找到: {path}");
    }
}
